<!--
 * 角色管理--新增编辑角色
 * @author: hexiaozhen
 * @since: 2023-09-27
 * addEditRole.vue
-->
<template>
  <component
    :is="$route.name === 'AddRole' || $route.name === 'EditRole' ? 'div' : 'a-modal'"
    :class="$route.name === 'AddRole' || $route.name === 'EditRole' ? 'not-modal' : ''"
    v-model:visible="visibleModal"
    :footer="false"
    :title="type === 'add' ? '新增角色' : '编辑角色'"
    title-align="start"
    width="600px"
    :mask-closable="false"
    draggable
    @cancel="handleCancel"
  >
    <TableForm
      ref="formAndTableRef"
      :rules="rules"
      :showMore="false"
      :rowspan="24"
      :formItems="formItems"
      :formData="formData"
      class="tableForm"
    >
      <template v-slot:slotItem="{ field }">
        <div v-if="field.name === 'menuIds'">
          <a-checkbox-group v-model="formData.checkbox" @change="checkboxChange">
            <a-checkbox value="1">展开/折叠</a-checkbox>
            <a-checkbox value="2">全选/全不选</a-checkbox>
          </a-checkbox-group>
          <div class="tree">
            <a-tree
              ref="tree"
              :data="treeData"
              :field-names="{ key: 'menuId', title: 'menuName' }"
              v-model:checked-keys="formData.menuIds"
              v-model:half-checked-keys="halfCheckedKeys"
              :allow-clear="true"
              checkable
            ></a-tree>
          </div>
        </div>
      </template>
    </TableForm>
    <footer class="fr">
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleOk">确定</a-button>
    </footer>
  </component>
</template>

<script setup>
import { reactive, ref, onMounted, toRefs } from 'vue'
import TableForm from '@/components/tableForm/index.vue'
import system from '@/api/modules/system'
import { Message } from '@arco-design/web-vue'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
const props = defineProps({
  // 表单json配置项
  visible: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
    default: () => {
      return {
        type: '',
      }
    },
  },
})
const { visible, rowData } = toRefs(props)
const emit = defineEmits(['update:visible', 'submit'])
const type = ref(route.query.type ? route.query.type : rowData.value.type)
let visibleModal = ref(false) // 弹窗显示与隐藏
visibleModal.value = visible.value
const formAndTableRef = ref() // 表单
const tree = ref()
// 确定
const handleOk = () => {
  formAndTableRef.value.$refs.form.validate((valid) => {
    if (!valid) {
      const api = type.value === 'add' ? 'addRole' : 'editRole'
      const param = JSON.parse(JSON.stringify(formData.value))
      delete param.checkbox
      param.menuIds = [...param.menuIds, ...halfCheckedKeys.value]
      system[api](param).then((res) => {
        visibleModal.value = false
        Message.success(res.msg)
        emit('submit')
        emit('update:visible', false)
      })
    }
  })
}
// 取消
const handleCancel = () => {
  if (route.query.type) {
    router.go(-1)
  } else {
    visibleModal.value = false
    emit('update:visible', false)
  }
}
const halfCheckedKeys = ref([])
// 获取字典数据
const statusOptions = ref([])
// 表单配置
const formItems = reactive([
  { name: 'roleName', label: '角色名称', type: 'a-input' },
  { name: 'roleKey', label: '权限字符', type: 'a-input' },
  { name: 'roleSort', label: '角色顺序', type: 'a-input-number' },
  { name: 'status', label: '状态', type: 'a-radio', options: statusOptions },
  { name: 'menuIds', label: '菜单权限', type: 'slotItem' },
  { name: 'remark', label: '备注', type: 'a-textarea' },
])
let formData = ref({
  roleName: '',
  roleKey: '',
  roleSort: null,
  status: '0',
  menuIds: [],
  remark: '',
  checkbox: ['3'],
})

if (type.value === 'edit') {
  system.getRoleDetail(rowData.value.roleId).then((res) => {
    formData.value = { ...res.data, checkbox: [] }
    system.roleMenuTreeselect(rowData.value.roleId).then((res) => {
      formData.value.menuIds = res.data.checkedKeys
    })
  })
}

const rules = reactive({
  roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
  roleKey: [{ required: true, message: '权限字符不能为空', trigger: 'blur' }],
  roleSort: [{ required: true, message: '角色顺序不能为空', trigger: 'blur' }],
})
// 菜单权限复选框
const checkboxChange = (val) => {
  // 展开/折叠
  if (val.indexOf('1') !== -1) {
    tree.value.expandAll(true)
  } else {
    tree.value.expandAll(false)
  }
  // 全选/全不选
  if (val.indexOf('2') !== -1) {
    tree.value.checkAll(true)
  } else {
    tree.value.checkAll(false)
  }
}
//  数据字典
const getOption = () => {
  const param = { dictTypes: 'sys_normal_disable' }
  system.getDicts(param).then((res) => {
    statusOptions.value = res.data.sys_normal_disable.map((it) => ({
      label: it.dictLabel,
      value: it.dictValue,
    }))
  })
}
const treeData = ref([])
const getTree = () => {
  system.getMenuList().then((res) => {
    treeData.value = res.data
  })
}
onMounted(() => {
  getOption()
  getTree()
})
</script>

<style scoped lang="less">
.tree {
  height: 240px;
  margin-top: 5px;
  border: @border-1 solid #e5e6e7;
  border-radius: 4px;
  overflow: auto;
  padding: 0 10px;
}
</style>
